package com.musicserver.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.musicserver.common.R;
import com.musicserver.mapper.CommentMapper;
import com.musicserver.model.domain.Comment;
import com.musicserver.model.domain.UserSupport;
import com.musicserver.model.request.UserSupportRequest;
import com.musicserver.service.UserSupportService;
import com.musicserver.mapper.UserSupportMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* @author tch001
* @description 针对表【user_support】的数据库操作Service实现
* @createDate 2025-09-25 18:32:09
*/
@Service
public class UserSupportServiceImpl extends ServiceImpl<UserSupportMapper, UserSupport>
    implements UserSupportService{

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserSupportMapper userSupportMapper;

    @Override
    @Transactional
    public R toSupport(UserSupportRequest userSupportRequest) {
        Comment comment = commentMapper.selectById(userSupportRequest.getCommentId());
        if(null != comment){
            int up = comment.getUp();
            QueryWrapper<UserSupport> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("comment_id", userSupportRequest.getCommentId());
            queryWrapper.eq("user_id", userSupportRequest.getUserId());
            UserSupport userSupport = userSupportMapper.selectOne(queryWrapper);
            if(null == userSupport){//不存在，则点赞
                userSupport = new UserSupport();
                BeanUtils.copyProperties(userSupportRequest, userSupport);
                userSupportMapper.insert(userSupport);
                commentMapper.updateUpById(comment.getId(), 1);
                return R.success("点赞成功", up + 1);
            }else{  //存在，则取消点赞
                userSupportMapper.delete(queryWrapper);
                commentMapper.updateUpById(comment.getId(), -1);
                return R.success("您已取消点赞", up - 1);
            }
        }else{
            return R.error("评论不存在或已被删除！");
        }
    }
}




